<?php
class Image {
	private $width; // 画布宽度
	private $height; // 画布高度
	private $pixel; // 干扰点的数目
	private $line; // 干扰线的数目
	private $codeCount; // 验证码个数
	private $flag; // 验证码类型 1:数字 2：英文 3：数字英文
	public function __construct($params = array()) {
		$this->width = isset ( $params ['width'] ) ? $params ['width'] : 120;
		$this->height = isset ( $params ['height'] ) ? $params ['height'] : 25;
		$this->pixel = isset ( $params ['pixel'] ) ? $params ['pixel'] : 300;
		$this->line = isset ( $params ['line'] ) ? $params ['line'] : 4;
		$this->codeCount = isset ( $params ['codeCount'] ) ? $params ['codeCount'] : 4;
		$this->flag = isset ( $params ['flag'] ) ? $params ['flag'] : 1;
	}
	public function verifyCode() {
		// 创建画布
		$img = imagecreatetruecolor ( $this->width, $this->height );
		// 分配颜色
		$bgColor = imagecolorallocate ( $img, rand ( 200, 255 ), rand ( 200, 255 ), rand ( 200, 255 ) );
		// 颜色填充
		imagefill ( $img, 0, 0, $bgColor );
		/**
		 * *********************************************************************
		 */
		// 干扰点颜色
		$pixelColor = imagecolorallocate ( $img, rand ( 0, 150 ), rand ( 0, 150 ), rand ( 0, 150 ) );
		// 添加干扰点
		for($i = 0; $i < $this->pixel; $i ++) {
			$x = rand ( 0, $this->width - 1 );
			$y = rand ( 0, $this->height - 1 );
			imagesetpixel ( $img, $x, $y, $pixelColor );
		}
		/**
		 * *********************************************************************
		 */
		// 干扰线颜色
		$lineColor = imagecolorallocate ( $img, rand ( 0, 150 ), rand ( 0, 150 ), rand ( 0, 150 ) );
		// 添加干扰线
		for($i = 0; $i < $this->line; $i ++) {
			$x1 = rand ( 0, $this->width - 1 );
			$y1 = rand ( 0, $this->height - 1 );
			$x2 = rand ( 0, $this->width - 1 );
			$y2 = rand ( 0, $this->height - 1 );
			imageline ( $img, $x1, $y1, $x2, $y2, $lineColor );
		}
		/**
		 * *********************************************************************
		 */
		// 确定要随机的数据
		$data = array ();
		if ($this->flag == 1) {
			$data = array (
					0,
					1,
					2,
					3,
					4,
					5,
					6,
					7,
					8,
					9 
			);
		} else if ($this->flag == 2) {
			$data = array (
					'a',
					'b',
					'c',
					'd',
					'e',
					'f',
					'g' 
			);
		}
		$length = count ( $data ) - 1;
		$str = '';
		for($i = 0; $i < $this->codeCount; $i ++) {
			// 验证码颜色
			$codeColor = imagecolorallocate ( $img, rand ( 0, 150 ), rand ( 0, 150 ), rand ( 0, 150 ) );
			// 随机验证码
			$code = $data [rand ( 0, $length )];
			$str .= $code;
			// 确定验证码坐标
			
			// 向图片中写验证码
			$wi = $this->width / $this->codeCount;
			imagechar ( $img, 5, rand ( $wi * $i, $wi * ($i + 1) - 15 ), rand ( 0, $this->height / 2 ), $code, $codeColor );
		}
		session_start ();
		$_SESSION ['checkCode'] = $str;
		header ( 'Content-Type:image/png' );
		imagepng ( $img );
		imagedestroy ( $img );
	}
}

?>